package simpleGeom;

import java.util.Vector;

import processing.core.PGraphics;
import processing.core.PMatrix3D;
import processing.core.PVector;

public class Bezier {
	public Vector<PVector>controlPoints=new Vector<PVector>();
	public Bezier(Vector<PVector>controlPoints){
		this.controlPoints=controlPoints;
	}
	
	public Bezier(){
		
	}
	public void addControlPoint(PVector p){
		controlPoints.add(p);
	}
	public void addControlPoint(float x,float y,float z){
		addControlPoint(new PVector(x,y,z));
	}
public PVector getPoint(float t){
	
	Vector<PVector>cPts=new Vector<PVector>(controlPoints);
	while (cPts.size()>1){
		Vector<PVector>newPts=new Vector<PVector>();
		for (int i=0;i<cPts.size()-1;i++){
			PVector p1=cPts.get(i);
			PVector p2=cPts.get(i+1);
			PVector v=PVector.sub(p2, p1);
			v.mult(t);
			v.add(p1);
			newPts.add(v);
		}
		cPts=newPts;
	}
	return cPts.firstElement();
}
public PVector getTangent(float t){
	Vector<PVector>cPts=new Vector<PVector>(controlPoints);
	while (cPts.size()>2){
		Vector<PVector>newPts=new Vector<PVector>();
		for (int i=0;i<cPts.size()-1;i++){
			PVector p1=cPts.get(i);
			PVector p2=cPts.get(i+1);
			PVector v=PVector.sub(p2, p1);
			v.mult(t);
			v.add(p1);
			newPts.add(v);
		}
		cPts=newPts;
	}
	PVector p1=cPts.get(0);
	PVector p2=cPts.get(1);
	PVector v=PVector.sub(p2, p1);
	v.normalize();
	return v;
}
 
public void display(PGraphics pg,int i){
	PVector oldP = controlPoints.firstElement();
	for (int j = 0; j < i+1; j++) {
		PVector cPt = getPoint(j*1f / i);
		pg.line(oldP.x, oldP.y, oldP.z, cPt.x, cPt.y, cPt.z);
		oldP = cPt;
	}
}
public void getControlPts(PVector[]pts){
	for (int j = 0; j < pts.length; j++) {
		pts[j] = getPoint(j*1f / (pts.length-1));
	}
}
}
